<template>
  <div class="settings-container">
    <div class="settings-header">
      <h2>设置</h2>
    </div>
    
    <div class="settings-content">
      <el-form
        ref="settingsFormRef"
        :model="settingsForm"
        label-width="120px"
        class="settings-form"
      >
        <!-- 服务器设置 -->
        <el-card class="settings-card">
          <template #header>
            <span>服务器设置</span>
          </template>
          
          <el-form-item label="服务器地址">
            <el-input
              v-model="settingsForm.serverUrl"
              placeholder="请输入服务器地址"
              @blur="handleServerUrlChange"
            />
          </el-form-item>
          
          <el-form-item label="连接状态">
            <el-tag :type="isConnected ? 'success' : 'danger'">
              {{ isConnected ? '已连接' : '未连接' }}
            </el-tag>
          </el-form-item>
        </el-card>
        
        <!-- 通知设置 -->
        <el-card class="settings-card">
          <template #header>
            <span>通知设置</span>
          </template>
          
          <el-form-item label="桌面通知">
            <el-switch
              v-model="settingsForm.enableNotification"
              @change="handleNotificationChange"
            />
            <div class="setting-description">
              接收到新消息时显示桌面通知
            </div>
          </el-form-item>
          
          <el-form-item label="声音提醒">
            <el-switch
              v-model="settingsForm.enableSound"
              @change="handleSoundChange"
            />
            <div class="setting-description">
              新消息到达时播放提示音
            </div>
          </el-form-item>
          
          <el-form-item label="测试通知">
            <el-button @click="handleTestNotification">
              发送测试通知
            </el-button>
          </el-form-item>
        </el-card>
        
        <!-- 应用设置 -->
        <el-card class="settings-card">
          <template #header>
            <span>应用设置</span>
          </template>
          
          <el-form-item label="开机自启">
            <el-switch
              v-model="settingsForm.autoLaunch"
              :loading="autoLaunchLoading"
              @change="handleAutoLaunchChange"
            />
            <div class="setting-description">
              系统启动时自动运行应用
            </div>
          </el-form-item>
          
          <el-form-item label="最小化到托盘">
            <el-switch
              v-model="settingsForm.minimizeToTray"
              @change="handleMinimizeToTrayChange"
            />
            <div class="setting-description">
              关闭窗口时最小化到系统托盘
            </div>
          </el-form-item>
        </el-card>
        
        <!-- 数据管理 -->
        <el-card class="settings-card">
          <template #header>
            <span>数据管理</span>
          </template>
          
          <el-form-item label="清除数据">
            <el-button
              type="danger"
              @click="handleClearData"
            >
              清除所有消息
            </el-button>
            <div class="setting-description">
              清除本地存储的所有消息数据
            </div>
          </el-form-item>
        </el-card>
        
        <!-- 账户管理 -->
        <el-card class="settings-card">
          <template #header>
            <span>账户管理</span>
          </template>
          
          <el-form-item label="当前用户">
            <div class="user-info">
              <el-avatar :size="32">
                {{ user?.name?.charAt(0) || 'U' }}
              </el-avatar>
              <span class="user-name">{{ user?.name || '未知用户' }}</span>
            </div>
          </el-form-item>
          
          <el-form-item label="退出登录">
            <el-button
              type="danger"
              @click="handleLogout"
            >
              退出登录
            </el-button>
          </el-form-item>
        </el-card>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAuthStore } from '../stores/auth'
import { useMessageStore } from '../stores/message'
import { useSignalRStore } from '../stores/signalr'

const authStore = useAuthStore()
const messageStore = useMessageStore()
const signalRStore = useSignalRStore()

const settingsFormRef = ref()
const autoLaunchLoading = ref(false)

const user = computed(() => authStore.user)
const isConnected = computed(() => signalRStore.isConnected)

const settingsForm = reactive({
  serverUrl: authStore.serverUrl,
  enableNotification: JSON.parse(localStorage.getItem('enable_notification') || 'true'),
  enableSound: JSON.parse(localStorage.getItem('enable_sound') || 'true'),
  autoLaunch: false,
  minimizeToTray: JSON.parse(localStorage.getItem('minimize_to_tray') || 'true')
})

const handleServerUrlChange = () => {
  if (settingsForm.serverUrl !== authStore.serverUrl) {
    authStore.setServerUrl(settingsForm.serverUrl)
    ElMessage.success('服务器地址已更新')
  }
}

const handleNotificationChange = (value) => {
  localStorage.setItem('enable_notification', JSON.stringify(value))
  ElMessage.success(value ? '已开启桌面通知' : '已关闭桌面通知')
}

const handleSoundChange = (value) => {
  localStorage.setItem('enable_sound', JSON.stringify(value))
  ElMessage.success(value ? '已开启声音提醒' : '已关闭声音提醒')
}

const handleTestNotification = async () => {
  if (window.electronAPI) {
    const success = await window.electronAPI.showNotification({
      title: '测试通知',
      body: '这是一条测试通知消息',
      tag: 'test'
    })
    
    if (success) {
      ElMessage.success('测试通知已发送')
    } else {
      ElMessage.error('通知发送失败')
    }
  } else {
    ElMessage.warning('当前环境不支持系统通知')
  }
}

const handleAutoLaunchChange = async (value) => {
  if (!window.electronAPI) {
    ElMessage.warning('当前环境不支持开机自启设置')
    return
  }
  
  autoLaunchLoading.value = true
  
  try {
    const success = await window.electronAPI.setAutoLaunch(value)
    if (success) {
      ElMessage.success(value ? '已开启开机自启' : '已关闭开机自启')
    } else {
      ElMessage.error('设置开机自启失败')
      settingsForm.autoLaunch = !value // 恢复原状态
    }
  } catch (error) {
    console.error('设置开机自启失败:', error)
    ElMessage.error('设置开机自启失败')
    settingsForm.autoLaunch = !value
  } finally {
    autoLaunchLoading.value = false
  }
}

const handleMinimizeToTrayChange = (value) => {
  localStorage.setItem('minimize_to_tray', JSON.stringify(value))
  ElMessage.success(value ? '已开启最小化到托盘' : '已关闭最小化到托盘')
}

const handleClearData = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清除所有消息数据吗？此操作不可恢复。',
      '确认清除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    messageStore.clearAllMessages()
    ElMessage.success('所有消息数据已清除')
  } catch (error) {
    // 用户取消
  }
}

const handleLogout = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要退出登录吗？',
      '确认退出',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await authStore.logout()
    ElMessage.success('已退出登录')
  } catch (error) {
    // 用户取消
  }
}

const loadAutoLaunchStatus = async () => {
  if (window.electronAPI) {
    try {
      settingsForm.autoLaunch = await window.electronAPI.getAutoLaunch()
    } catch (error) {
      console.error('获取开机自启状态失败:', error)
    }
  }
}

onMounted(() => {
  loadAutoLaunchStatus()
})
</script>

<style lang="scss" scoped>
.settings-container {
  height: 100vh;
  background: $bg-color;
}

.settings-header {
  padding: 24px;
  background: white;
  border-bottom: 1px solid $border-color;
  
  h2 {
    margin: 0;
    color: $text-color-primary;
    font-size: 20px;
    font-weight: 600;
  }
}

.settings-content {
  padding: 24px;
  overflow-y: auto;
  height: calc(100vh - 89px);
}

.settings-form {
  max-width: 600px;
}

.settings-card {
  margin-bottom: 20px;
  
  :deep(.el-card__header) {
    background: $bg-color;
    font-weight: 500;
  }
}

.setting-description {
  font-size: 12px;
  color: $text-color-secondary;
  margin-top: 4px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  
  .user-name {
    font-weight: 500;
    color: $text-color-primary;
  }
}
</style>